<template>
  <div>
    <!-- 表单 -->
    <el-form ref="form" :model="form" size="mini" label-width="150px" :rules="rules" style="margin-top:20px;" label-position="left">
      <el-form-item label="供应商名称：">
        <el-col :span="5">
          <span>{{form.supplierName}}</span>
        </el-col>
      </el-form-item>
      <el-form-item label="采购价格协议名称：" prop="agreementName">
        <el-col :span="5">
          <span>{{form.agreementName}}</span>
        </el-col>
      </el-form-item>
      <el-form-item label="协议起止时间：" prop="dateRange">
        <el-date-picker v-model="form.dateRange" type="daterange" format="yyyy年 MM 月 dd 日" value-format="yyyy-MM-dd" range-separator="至" start-placeholder="协议开始日期" end-placeholder="协议结束日期"> </el-date-picker>
      </el-form-item>
    </el-form>

    <!-- 商品列表 -->
    <div class="tableMain petable">
      <el-form :model="form" size="mini" style="width:90%;">
        <el-form-item>
          <el-button type="primary" size="mini" @click="_handleAddGoods()" style="float:right;">选择商品</el-button>
        </el-form-item>
      </el-form>

      <!-- 原来的商品 -->
      <h3 class="table-title">协议原有商品列表</h3>
      <el-table :data="tableData" :row-class-name="tableRowClassName">
        <el-table-column type="index" label="序号" align="center"></el-table-column>
        <el-table-column prop="goodsName" label="商品名称" align="center"></el-table-column>
        <el-table-column prop="goodsSpec" label="规格型号" align="center">
          <template slot-scope="scope">
            <div v-for="(item,index) in scope.row.goodsSpec" :key="index">
              <span v-if="item!=null">{{item.paramName}} :</span>
              <span v-if="item!=null"> {{item.paramValue}} </span>
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="purchaseUnit" label="采供单位" align="center"></el-table-column>
        <el-table-column prop="goodsPrice" label="单价" align="center">
          <template slot-scope="scope">
            <sd-input :val.sync="scope.row.goodsPrice"></sd-input>
          </template>
        </el-table-column>
        <el-table-column prop="isFreight" label="含运费" align="center">
          <template slot-scope="scope">
            <el-switch active-color="#13ce66" inactive-color="#ff4949" active-value="1" inactive-value="0" v-model="scope.row.isFreight"></el-switch>
          </template>
        </el-table-column>
        <el-table-column prop="freight" align="center" label="运费">
          <template slot-scope="scope">
            <sd-input :val.sync="scope.row.freight" v-show="scope.row.isFreight == '0'"></sd-input>
          </template>
        </el-table-column>
      </el-table>

      <page-unit :pageData="pageData" :func="_getOrderPriceAgreementDetail"></page-unit>

      <!-- 追加的商品 -->
      <h3 class="table-title">协议追加商品列表</h3>
      <el-table :data="tableDataNew">
        <el-table-column type="index" label="序号" align="center"></el-table-column>
        <el-table-column prop="goodsName" label="商品名称" align="center"></el-table-column>
        <el-table-column prop="goodsSpec" label="规格型号" align="center">
          <template slot-scope="scope">
            <div v-for="(item,index) in scope.row.goodsSpec" :key="index">
              <span v-if="item!=null">{{item.paramName}} :</span>
              <span v-if="item!=null"> {{item.paramValue}} </span>
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="purchaseUnit" label="采供单位" align="center"></el-table-column>
        <el-table-column prop="goodsPrice" label="单价" align="center">
          <template slot-scope="scope">
            <sd-input :val.sync="scope.row.goodsPrice"></sd-input>
          </template>
        </el-table-column>
        <el-table-column prop="isFreight" label="含运费" align="center">
          <template slot-scope="scope">
            <el-switch active-color="#13ce66" inactive-color="#ff4949" active-value="1" inactive-value="0" v-model="scope.row.isFreight"></el-switch>
          </template>
        </el-table-column>
        <el-table-column prop="freight" align="center" label="运费">
          <template slot-scope="scope">
            <sd-input :val.sync="scope.row.freight" v-show="scope.row.isFreight == '0'"></sd-input>
          </template>
        </el-table-column>
        <el-table-column align="center" label="操作">
          <template slot-scope="scope">
            <el-button size="mini" v-show="scope.row.isOrigin!==true" @click="_handleDelete(scope.$index)" type="text">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <el-form :model="form" size="mini" style="width:90%;">
        <el-form-item>
          <el-button type="primary" size="mini" @click="onSubmit('form')" style="margin-top:20px;float:right;">确认</el-button>
          <el-button size="mini" @click="goBack()" style="margin-top:20px;float:right;margin-right:20px;">取消</el-button>
        </el-form-item>
      </el-form>
    </div>

    <!-- 商品选择弹出框 -->
    <el-dialog title="商品选择" :visible.sync="goodsClass.dialog" :closeOnClickModal='false' :closeOnPressEscape='false'>
      <el-form size="mini">
        <el-form-item label="" label-width="0">
          <el-input v-model="selectData.keyWord" placeholder="输入商品名称/货号/条码搜索" style="width:200px;">
            <i slot="suffix" class="el-input__icon el-icon-search" @click="goodsClass.handleSearch(_findGoodsShopPage, goodsClass.pageData)"></i>
          </el-input>
        </el-form-item>
      </el-form>

      <el-table :data="goodsClass.tableData" ref="multipleTablegood" tooltip-effect="dark" @selection-change="goodsClass.handleMultipleSelect" :row-key="getRowKeys">
        <el-table-column type="selection" :reserve-selection="true" width="55"></el-table-column>
        <el-table-column type="index" width="50" label="序号" align="center"></el-table-column>
        <el-table-column prop="goodsCode" label="商品货号" align="center"></el-table-column>
        <el-table-column prop="barCode" label="商品条码" align="center"></el-table-column>
        <el-table-column prop="name" label="商品名称" align="center"></el-table-column>
        <el-table-column prop="goodsSpec" label="规格型号" align="center">
          <template slot-scope="scope">
            <div v-for="(item,index) in scope.row.goodsSpec" :key="index">
              <span v-if="item!=null">{{item.paramName}} :</span>
              <span v-if="item!=null"> {{item.paramValue}} </span>
            </div>
          </template>
        </el-table-column>
      </el-table>
      <page-unit :pageData="goodsClass.pageData" :func="_findGoodsShopPage"></page-unit>

      <el-form label-width="0" size="mini">
        <el-form-item>
          <el-button type="primary" @click="handleSelectGoods()" style="margin-top:20px;float:right;">确认</el-button>
          <el-button @click="goodsClass.dialog=false" style="margin-top:20px;float:right;margin-right:20px;">取消</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>
  </div>
</template>

<script>
import { mapState } from "vuex";
import pageUnit from "components/Page";
import sdInput from "@/components/SdInput";
import u from "@/util";
import { TableHandle } from "@/util/class";
import {
  updateOrderPriceAgreement,
  findGoodsShopPage,
  getOrderPriceAgreementDetail,
  updateOrderPriceAgreementStatus
} from "@/api";

export default {
  computed: mapState(["sub", "merchantId", "userName", "userInfo"]),
  components: { pageUnit, sdInput },

  data () {
    return {
      getRowKeys (row) {
        return row.id; // 获取row的key值
      },
      isEdit: false,
      form: {
        agreementId: '',  // 协议id
        creater: '',  // 创建人
        supplierId: '',  // 供应商ID
        supplierName: '',  // 供应商名称
        isLogin: '',  // 供应商是否入驻
        customerId: '',  // 企业客户ID
        customerName: '',  // 企业客户名称
        agreementType: 0,  // 协议类型 0-自建 1-同步
        status: '',  // 协议状态
        dateRange: [],
        startDate: '',  // 开始时间
        endDate: '',  // 结束时间
        agreementName: '',  // 协议名称
      },
      tableData: [],  // 价格协议的商品列表
      tableDataOrigin: [],
      goodsClass: new TableHandle(),
      selectData: {
        keyWord: ''
      },
      pageData: {
        pageSize: 20,
        pageNum: 1,
        currentPage: 1,
        totalItems: 0,
        pageSizeArr: [5, 10, 20]
      },
      rules: {
        agreementName: [{ required: true, message: '请输入采购价格协议名称', trigger: 'blur' }],
        dateRange: [{ required: true, message: '请选择开始日期', trigger: 'change' }],
      },
      tableDataNew: []
    }
  },

  created () {
    this.form.agreementId = u.getQuery().agreementId  // 协议id
    this.form.agreementType = Number(u.getQuery().agreementType)  // 协议类型
    this.form.status = Number(u.getQuery().status)
    this.form.supplierId = u.getQuery().supplierId  // 供应商id
    this.form.supplierName = u.getQuery().supplierName  // 供应商id
    this.form.isLogin = u.getQuery().isLogin  // 供应商是否入驻
  },

  mounted () {
    this._getOrderPriceAgreementDetail(this.pageData.pageSize, 1)
  },

  methods: {
    tableRowClassName ({ row, rowIndex }) {
      if (row.isUpdate === 1) {
        return 'warning-row';
      }
      return '';
    },

    // 查看价格协议详情
    _getOrderPriceAgreementDetail (pageSize, pageNum) {
      getOrderPriceAgreementDetail({
        agreementId: this.form.agreementId,
        pageSize: pageSize,
        pageNum: pageNum
      }).then(res => {
        if (res.data.goodsList !== undefined) {
          res.data.goodsList.forEach(i => {
            i.isFreight = i.isFreight.toString()
            i.isOrigin = true
          })
          this.tableData = JSON.parse(JSON.stringify(res.data.goodsList))
          this.tableDataOrigin = JSON.parse(JSON.stringify(res.data.goodsList))
          this.pageData.totalItems = res.data.pageTotal
        }
        this.form.agreementId = res.data.id
        this.form.supplierId = res.data.supplierId
        this.form.supplierName = res.data.supplierName
        this.form.customerId = res.data.customerId
        this.form.customerName = res.data.customerName
        this.form.agreementType = res.data.agreementType
        this.form.status = res.data.status
        this.form.startDate = u.foryear(res.data.startDate)
        this.form.endDate = u.foryear(res.data.endDate)
        this.form.dateRange = []
        this.form.dateRange.push(u.foryear(res.data.startDate))
        this.form.dateRange.push(u.foryear(res.data.endDate))
        this.form.agreementName = res.data.agreementName
      })
    },

    // 提交
    onSubmit (formName) {
      for (let i = 0; i < this.tableData.length; i++) {
        if (Number(this.tableData[i].isFreight) === 1) {
          this.tableData[i].freight = 0
        } else {
          if (this.tableData[i].freight === '' || this.tableData[i].freight === 0 || this.tableData[i].freight == undefined) {
            this.$message.error('输入运费不能为0或空！')
            return false
          }
        }
        if (this.tableData[i].goodsPrice === '' || this.tableData[i].goodsPrice === undefined) {
          this.$message.error('输入价格不能为空！')
          return false
        }
      }
      for (let i = 0; i < this.tableDataNew.length; i++) {
        if (Number(this.tableDataNew[i].isFreight) === 1) {
          this.tableDataNew[i].freight = 0
        } else {
          if (this.tableDataNew[i].freight == '' || this.tableDataNew[i].freight == 0 || this.tableDataNew[i].freight == undefined) {
            this.$message.error('输入运费不能为0或空！')
            return false
          }
        }
        if (this.tableDataNew[i].goodsPrice == '' || this.tableDataNew[i].goodsPrice == undefined) {
          this.$message.error('输入价格不能为空！')
          return false
        }
      }
      let arr = []
      for (let i = 0; i < this.tableData.length; i++) {
        let flag = false
        for (let j = 0; j < this.tableDataOrigin.length; j++) {
          if (
            this.tableDataOrigin[j].isFreight === this.tableData[i].isFreight &&
            this.tableDataOrigin[j].freight === this.tableData[i].freight &&
            this.tableDataOrigin[j].goodsPrice === this.tableData[i].goodsPrice
          ) {
            flag = true
          }
        }
        if (!flag) {
          arr.push(this.tableData[i])
        }
      }
      this.form.startDate = this.form.dateRange[0]
      this.form.endDate = this.form.dateRange[1]
      this.$refs[formName].validate((valid) => {
        if (valid) {
          arr = arr.concat(this.tableDataNew)
          // console.log(arr)
          // return
          if (arr.length !== 0) {
            this.tableData = JSON.parse(JSON.stringify(arr))
            this._updateOrderPriceAgreement()
          } else {
            this.tableData = []
            this._updateOrderPriceAgreement()
          }
        } else {
          return false;
        }
      });
    },

    // 修改价格协议
    _updateOrderPriceAgreement () {
      updateOrderPriceAgreement({
        orderPriceAgreement: {
          id: this.form.agreementId,
          creater: this.merchantId,
          supplierId: this.form.supplierId,
          supplierName: this.form.supplierName,
          customerId: this.merchantId,
          customerName: this.form.customerName,
          agreementType: this.form.agreementType,
          startDate: this.form.startDate,
          endDate: this.form.endDate,
          agreementName: this.form.agreementName,
        },
        goodsList: JSON.stringify(this.tableData)
      }).then(res => {
        history.back()
      })
    },

    // 查询商品列表（用于添加价格协议）
    _findGoodsShopPage (pageSize, pageNum) {
      this.form.startDate = this.form.dateRange[0]
      this.form.endDate = this.form.dateRange[1]
      findGoodsShopPage({
        supplierId: this.form.supplierId,
        customerId: this.merchantId,
        startDate: this.form.startDate,
        endDate: this.form.endDate,
        searchInfo: this.selectData.keyWord,
        pageNo: pageNum,
        pageSize: pageSize,
        shopId: this.merchantId
      }).then(res => {
        this.goodsClass.tableData = res.data.list
        this.goodsClass.tableData.forEach(i => {
          i.goodsId = i.id
          i.goodsSpec = i.parameter
        })
        this.goodsClass.pageData.totalItems = res.data.total
      })
    },

    // 点击选择商品按钮
    _handleAddGoods () {
      if (this.form.startDate == '' || this.form.endDate == '') {
        this.$message.error('请先选择协议时间')
        return
      } else {
        this.goodsClass.pageData.pageNum = 1
        this._findGoodsShopPage(this.goodsClass.pageData.pageSize, this.goodsClass.pageData.currentPage)
        this.goodsClass.dialog = true
      }
    },

    // 商品弹窗确认选择
    handleSelectGoods () {
      if (this.goodsClass.isSelect(2, this, '请先选择商品！')) {
        this.goodsClass.multipleSelectTable.forEach(i => {
          i.goodsId = i.id
          i.goodsName = i.name
          i.goodsUnit = i.goodsPackParameterId
          i.goodsSpec = i.parameter
          i.isFreight = '0'
        })
        this.goodsClass.multipleSelectTable.forEach(i => {
          delete i.id
        })
        let newData = []
        for (let i = 0; i < this.goodsClass.multipleSelectTable.length; i++) {
          if (!(this.tableData.some(item => item.goodsId == this.goodsClass.multipleSelectTable[i].goodsId))) {
            newData.push(this.goodsClass.multipleSelectTable[i])
          }
        }
        this.tableDataNew = this.tableDataNew.concat(JSON.parse(JSON.stringify(newData)))
        let newArr = []
        this.tableDataNew.forEach(cur => {
            if(!(newArr.some(i => i.goodsId == cur.goodsId))) {
                newArr.push(cur)
            }
        })
        this.tableDataNew = newArr
        this.goodsClass.dialog = false
      }
    },

    _handleDelete (index) {
      this.tableDataNew.splice(index, 1)
    },

    goBack () {
      history.back()
    }
  }
}
</script>

<style scoped>
.el-table .warning-row {
  background: oldlace;
}
.petable .pageblock {
  width: 93%;
}
.table-title {
  height: 50px;
  line-height: 50px;
  font-size: 15px;
  font-weight: 500;
}
</style>
